package com.ktjiaoyu.crm.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktjiaoyu.crm.pojo.Right;
import com.ktjiaoyu.crm.pojo.Role;
import com.ktjiaoyu.crm.service.RightService;
import com.ktjiaoyu.crm.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName : RoleControoler
 * @Description :
 * @Author : Lzz
 * @Date: 2023/11/22 10:50:30
 */
@Controller
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Resource
    private RightService rightService;


    /**
     * 获取所有角色信息
     * @return
     */
    @RequestMapping("/role/json")
    @ResponseBody
    public List<Role> findAllRoles(){

        //查询所有角色信息
        List<Role> roles = roleService.findAllRoleList();

        return roles;
    }

    /**
     * 角色列表
     * @param model
     * @param roleName
     * @param pageIndex
     * @return
     */
    @RequestMapping(value = "/role/list")
    public String list(Model model, String roleName, @RequestParam(value = "pageIndex",defaultValue = "1") Integer pageIndex){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(StrUtil.isNotEmpty(roleName),"role_name", roleName);
        //查询角色列表
        Page<Role> rolePage = roleService.page(new Page(pageIndex, 5),queryWrapper);
        model.addAttribute("roleName",roleName);
        model.addAttribute("rolePage",rolePage);
        return "role/list";
    }

    /**
     * 去到新增角色页面
     */
    @GetMapping("/role/add")
    public String toAdd(Model model) {
        // 获得所有权限数据展示到页面供选择
        List<Right> rights = rightService.list();
        // 设置到作用域
        model.addAttribute("rights", rights);
        return "role/add";
    }

    /**
     * 执行新增或修改角色
     */
    @PostMapping("/role/save")
    public String save(Role role, String[] rightCodes) {
        // 在没有选择任何权限时，容错处理
        rightCodes = rightCodes == null ? new String[0] : rightCodes;
        // 打印 最终为角色选择的权限，复选框使用字符串数组接收
        //System.out.println(new JSONArray(Arrays.asList(rightCodes)).toString());

        // 如果角色的启用状态为null则设置为0
        if (role != null && role.getRoleFlag() == null) {
            role.setRoleFlag(0);
        }
        // 如果有带ID就修改，没有带ID则添加
        roleService.saveRoleAndRight(role, rightCodes);

        return "redirect:/role/list"; // 重定向
    }

}
